<template>
  <div class="consult-pay-page" v-if="consultStore.consult.payment && patient">
    <cp-nav-bar title="支付" />
    <div class="pay-info">
      <p class="tit">图文问诊 {{ consultStore.consult.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <div class="pay-space"></div>
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="`${patient.name} | ${patient.genderValue} | ${patient.age}岁`"
      ></van-cell>
      <van-cell
        title="病情描述"
        :label="consultStore.consult.illnessDesc"
      ></van-cell>
      <van-cell title="患病时长" :label="illnessTimeStr"></van-cell>
      <van-cell
        title="此次病情是否去医院就诊过？"
        :label="illnessReConsultStr"
      ></van-cell>
      <van-cell title="病情图片">
        <!-- 预览已上传的图片 -->
        <template
          #label
          v-if="
            consultStore.consult.pictures &&
            consultStore.consult.pictures.length > 0
          "
        >
          <div class="illness-img">
            <van-image
              v-for="item in consultStore.consult.pictures"
              :key="item.id || item.objectUrl"
              :src="item.content || item.url"
              fit="cover"
              width="80"
              height="80"
              radius="8"
              @click="
                previewImage(
                  item.content || item.url,
                  consultStore.consult.pictures
                )
              "
            />
          </div>
        </template>
      </van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree">
        我已同意 <span class="text">支付协议</span>
      </van-checkbox>
    </div>
    <van-submit-bar
      button-type="primary"
      :price="consultStore.consult.payment * 100"
      button-text="立即支付"
      text-align="left"
      @click="submit"
      :loading="loading"
    />
    <!-- 支付抽屉，控制面板 -->
    <van-action-sheet
      v-model:show="show"
      title="选择支付方式"
      :close-on-popstate="false"
      :before-close="onClose"
    >
      <div class="pay-type">
        <p class="amount">￥{{ consultStore.consult.payment.toFixed(2) }}</p>
        <van-cell-group>
          <van-cell title="微信支付" @click="paymentMethod = 0">
            <template #icon><cp-icon name="consult-wechat" /></template>
            <template #extra
              ><van-checkbox :checked="paymentMethod === 0"
            /></template>
          </van-cell>
          <van-cell title="支付宝支付" @click="paymentMethod = 1">
            <template #icon><cp-icon name="consult-alipay" /></template>
            <template #extra
              ><van-checkbox :checked="paymentMethod === 1"
            /></template>
          </van-cell>
        </van-cell-group>
        <div class="btn">
          <van-button type="primary" round block @click="pay"
            >立即支付</van-button
          >
        </div>
      </div>
    </van-action-sheet>
  </div>
  <div class="consult-pay-page" v-else>
    <cp-nav-bar title="支付" />
    <!-- 骨架组件 -->
    <van-skeleton title :row="10" style="margin-top: 18px" />
  </div>
</template>
<script setup lang="ts">
import { ConsultType, IllnessTime } from '@/enums'
import { createConsultOrder, getConsultOrderPre } from '@/services/consult'
import { getPatientDetail } from '@/services/user'
import { useConsultStore, useUserStore } from '@/stores'
import type { Consult, PartialConsult } from '@/types/consult'
import type { Patient } from '@/types/user'
import { showConfirmDialog, showDialog, showToast } from 'vant'
import { computed, onMounted, ref } from 'vue'
import { onBeforeRouteLeave, useRouter } from 'vue-router'
// 在 script 部分添加
import { ImagePreview } from 'vant'

const consultStore = useConsultStore()
const userStore = useUserStore()
// 修改 loadData 函数如下：
const loadData = async () => {

  console.log('获取订单信息')
  console.log("consultStore",consultStore.consult)
  if (consultStore.consult.type === ConsultType.Fast) {
    consultStore.consult.payment = 39
    return
  }
  const doctorId = consultStore.consult.doctorId
  console.log('获取订单预支付信息，医生ID：', doctorId)
  if (!doctorId) {
    showToast('医生信息缺失，请重新选择')
    return
  }
  console.log("this")
  const res = await getConsultOrderPre(doctorId)
  console.log("res",res)
  consultStore.consult.payment = res.data
}
// 患者详情
const patient = ref<Patient>()
const loadPatient = async () => {
  const userId = userStore.user?.id
  const patientId = consultStore.consult.patientId
  if (!userId || !patientId) return
  const res = await getPatientDetail(userId, patientId)
  let { id, name, idCard, gender, genderValue, age, phone } = res.data
  if (gender === '男') {
    genderValue = '男'
    gender = 0
  } else {
    genderValue = '女'
    gender = 1
  }
  patient.value = { id, name, idCard, gender, genderValue, age, phone }
}

type Key = keyof PartialConsult
onMounted(() => {
  const { consult } = consultStore
  // 生成订单需要的信息不完整的时候需要提示
  const validKeys: Key[] = [
    'type',
    'illnessDesc',
    'illnessTime',
    'reConsultFlag',
    'patientId'
  ]
  const valid = validKeys.every((key) => consult[key] !== undefined)
  if (!valid) {
    return showDialog({
      title: '温馨提示',
      message:
          '问诊信息不完整请重新填写，如有未支付的问诊订单可在问诊记录中继续支付！',
      closeOnPopstate: false
    }).then(() => {
      router.push('/consult/illness')
    })
  }
  loadData()
  loadPatient()
})

// 同意
const agree = ref(false)

// 支付方式选择
const paymentMethod = ref(0)

// 支付方法
const pay = async () => {
  console.log('开始支付，支付方式：', paymentMethod.value)
  window.location.href = 'http://localhost:9002/pay/consult/' + orderId.value
  // window.location.href = 'http://localhost/room?orderId=' + orderId.value
}

// 生成订单

const show = ref(false)
const loading = ref(false)
const orderId = ref('')
const submit = async () => {
  if (!agree.value) return showToast('请勾选我已同意支付协议')

  // 避免重复生成订单
  if (!orderId.value) {
    loading.value = true
    try {
      // 创建订单 - 确保数据类型正确
      const consultData = consultStore.consult as Consult
      const res = await createConsultOrder(consultData)
      orderId.value = res.data
      loading.value = false
      // consultStore.clear();
    } catch (error) {
      loading.value = false
      console.error('创建订单失败:', error)
      showToast('创建订单失败，请重试')
      return
    }
  }

  // 打开支付弹窗
  show.value = true
}

// 提示1：取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？
// 提示2：问诊信息不完整请重新填写，如有未支付的问诊订单可在问诊记录中继续支付！

// 用户引导
onBeforeRouteLeave(() => {
  if (orderId.value) return false
})

const router = useRouter()
const onClose = () => {
  return showConfirmDialog({
    title: '温馨提示',
    message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    cancelButtonText: '狠心离开',
    confirmButtonText: '继续支付'
  })
      .then(() => {
        return false
      })
      .catch(() => {
        orderId.value = ''
        router.push('/user/consult')
        return true
      })
}

const illnessTimeStr = computed(() => {
  switch (consultStore.consult.illnessTime) {
    case IllnessTime.Week:
      return '一周内'
    case IllnessTime.Month:
      return '一月内'
    case IllnessTime.HalfYear:
      return '半年内'
    case IllnessTime.More:
      return '半年以上'
    default:
      return ''
  }
})

const illnessReConsultStr = computed(() => {
  return consultStore.consult.reConsultFlag ? '是' : '否'
})

// 图片预览方法
const previewImage = (current: string, images: any[]) => {
  const imageUrls = images.map((item) => item.content || item.url)
  ImagePreview.open({
    images: imageUrls,
    startPosition: imageUrls.indexOf(current)
  })
}
</script>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
}
.pay-info {
  display: flex;
  padding: 15px;
  flex-wrap: wrap;
  align-items: center;
  .tit {
    width: 100%;
    font-size: 16px;
    margin-bottom: 10px;
  }
  .img {
    margin-right: 10px;
    width: 38px;
    height: 38px;
    border-radius: 4px;
    overflow: hidden;
  }
  .desc {
    flex: 1;
    > span {
      display: block;
      color: var(--cp-tag);
      &:first-child {
        font-size: 16px;
        color: var(--cp-text2);
      }
    }
  }
}
.pay-price {
  ::v-deep() {
    .vam-cell__title {
      font-size: 16px;
    }
    .van-cell__value {
      font-size: 16px;
      color: var(--cp-price);
    }
  }
}
.pay-space {
  height: 12px;
  background-color: var(--cp-bg);
}
.pay-schema {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  .text {
    color: var(--cp-primary);
  }
}
::v-deep() {
  .van-submit-bar__button {
    font-weight: normal;
    width: 160px;
  }
}

.illness-img {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-top: 8px;

  .van-image {
    border: 1px solid var(--cp-line);
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      border-color: var(--cp-primary);
      transform: scale(1.05);
    }
  }
}
</style>
